<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="vjImUBDCK8Rg9G13vkIip_GUsZTtVV6s-XdSk81-jzA" />













  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kotlin,Generics," />





  <link rel="alternate" href="/atom.xml" title="旺仔的个人博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.png?v=5.1.2" />






<meta name="description" content="泛型，即“参数化类型”，顾名思义，就是将类型由原来的具体的类型参数化，类似于方法中的变量参数，此时类型也定义成参数形式（可以称之为类型形参），然后在使用/调用时传入具体的类型（类型实参）。 接下来学习Kotlin中的泛型，Kotlin的泛型为类型安全提供保证，相比与Java更安全。">
<meta name="keywords" content="Kotlin,Generics">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin学习_泛型（Generics）">
<meta property="og:url" content="http://www.jowanxu.top/2017/05/31/Kotlin学习_泛型/index.html">
<meta property="og:site_name" content="旺仔的个人博客">
<meta property="og:description" content="泛型，即“参数化类型”，顾名思义，就是将类型由原来的具体的类型参数化，类似于方法中的变量参数，此时类型也定义成参数形式（可以称之为类型形参），然后在使用/调用时传入具体的类型（类型实参）。 接下来学习Kotlin中的泛型，Kotlin的泛型为类型安全提供保证，相比与Java更安全。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-a0fe4dc1b01ad8ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-2fbaa3c0ba7c9be5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-80d92186bcfa4974.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-29T00:20:21.558Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Kotlin学习_泛型（Generics）">
<meta name="twitter:description" content="泛型，即“参数化类型”，顾名思义，就是将类型由原来的具体的类型参数化，类似于方法中的变量参数，此时类型也定义成参数形式（可以称之为类型形参），然后在使用/调用时传入具体的类型（类型实参）。 接下来学习Kotlin中的泛型，Kotlin的泛型为类型安全提供保证，相比与Java更安全。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/1241355-a0fe4dc1b01ad8ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.jowanxu.top/2017/05/31/Kotlin学习_泛型/"/>





  <title>Kotlin学习_泛型（Generics） | 旺仔的个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>
    <a href="https://github.com/wangzailfm"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">旺仔的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">叫我旺仔<br/>Android Developer</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.jowanxu.top/2017/05/31/Kotlin学习_泛型/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jowan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="旺仔的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kotlin学习_泛型（Generics）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-31T09:31:59+08:00">
                2017-05-31
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2017-11-29T08:20:21+08:00">
                2017-11-29
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Kotlin/" itemprop="url" rel="index">
                    <span itemprop="name">Kotlin</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 文章热度</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <br/>
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">文章字数</span>
                
                <span title="文章字数">
                  1,928 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长需</span>
                
                <span title="阅读时长需">
                  8 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://upload-images.jianshu.io/upload_images/1241355-a0fe4dc1b01ad8ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Interoperable"></p>
<p>泛型，即“参数化类型”，顾名思义，就是将类型由原来的具体的类型参数化，类似于方法中的变量参数，此时类型也定义成参数形式（可以称之为类型形参），然后在使用/调用时传入具体的类型（类型实参）。</p>
<p>接下来学习Kotlin中的泛型，Kotlin的泛型为类型安全提供保证，相比与Java更安全。</p>
<a id="more"></a>
<h2 id="泛型"><a href="#泛型" class="headerlink" title="泛型"></a>泛型</h2><p>在Java中经常会用到泛型：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Box</span>&lt;<span class="title">T</span>&gt;</span>&#123;</div><div class="line">    <span class="keyword">private</span> T var ; </div><div class="line">&#125;</div><div class="line"><span class="comment">// 使用</span></div><div class="line">Box&lt;String&gt; box = <span class="keyword">new</span> Box&lt;String&gt;();</div></pre></td></tr></table></figure></p>
<p>与Java一样，Kotlin中也用到了泛型：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Box</span>&lt;<span class="type">T</span>&gt;</span>(t: T) &#123;</div><div class="line">    <span class="keyword">var</span> value = t</div><div class="line">&#125;</div><div class="line"><span class="comment">// 使用</span></div><div class="line"><span class="keyword">val</span> box: Box&lt;<span class="built_in">Int</span>&gt; = Box&lt;<span class="built_in">Int</span>&gt;(<span class="number">1</span>)</div></pre></td></tr></table></figure></p>
<p>与Java不一样的是，Kotlin在可以推断出参数的情况下，如在构造函数参数上推测出等等，可是省去类型，如上面创建的实例传入的1是<code>Int</code>类型：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> box = Box(<span class="number">1</span>)</div></pre></td></tr></table></figure></p>
<p>而在Java中是不能这样做。</p>
<h2 id="变异-Variance"><a href="#变异-Variance" class="headerlink" title="变异(Variance)"></a>变异(Variance)</h2><p>在这里我们先来了解下Java泛型中的通配符，在<a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html" target="_blank" rel="external">Effective Java</a>中Item 28中写到: <em>Use bounded wildcards to increase API flexibility</em>，意思是使用通配符为了提高API的使用灵活性。<br>Java中使用<code>?</code>来表示通配符：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T extends Comparable&lt;? <span class="keyword">super</span> T&gt;&gt; <span class="function"><span class="keyword">void</span> <span class="title">sort</span><span class="params">(List&lt;T&gt; list)</span> </span>&#123;</div><div class="line">    Object[] array = list.toArray();</div><div class="line">    Arrays.sort(array);</div><div class="line">    <span class="keyword">int</span> i = <span class="number">0</span>;</div><div class="line">    ListIterator&lt;T&gt; it = list.listIterator();</div><div class="line">    <span class="keyword">while</span> (it.hasNext()) &#123;</div><div class="line">        it.next();</div><div class="line">        it.set((T) array[i++]);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在Java中，泛型是不可变的，如<code>List&lt;String&gt;</code>不是<code>List&lt;Object&gt;</code>的子类：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">List&lt;String&gt; strs = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">List&lt;Object&gt; objs = strs; <span class="comment">// 这是错误的，类型不匹配</span></div></pre></td></tr></table></figure></p>
<p>如果上面的操作是正确的，那么会在使用时造成类型不匹配的问题：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">objs.add(<span class="number">1</span>); <span class="comment">// 添加一个int类型到String的List里面</span></div><div class="line">String s = strs.get(<span class="number">0</span>); <span class="comment">// 会报ClassCastException: Cannot cast Integer to String的错误</span></div></pre></td></tr></table></figure></p>
<p>所以Java的泛型会被设计成不可变的类型，就是为了确保运行时类型安全，但是这样同样会带来一些影响。<br>举个例子，定义一个泛型接口<code>Collection</code>，里面有<code>addAll()</code>方法：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Collection</span>&lt;<span class="title">E</span>&gt; ... </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">addAll</span><span class="params">(Collection&lt;E&gt; items)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>由于Java的泛型是不可变的，所以下面的代码是做不到的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">copyAll</span><span class="params">(Collection&lt;Object&gt; to, Collection&lt;String&gt; from)</span> </span>&#123;</div><div class="line">     to.addAll(from); <span class="comment">// 这是错误的，Collection&lt;String&gt;不是Collection&lt;Object&gt;的子类</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>为了解决上面的问题，Java中使用了类型通配符方式，如<code>? extends T</code>表示<code>T</code>及<code>T</code>的子类参数都可以使用，所以<code>Collection</code>的<code>addAll()</code>方法是这样写的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Collection</span>&lt;<span class="title">E</span>&gt; ... </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">addAll</span><span class="params">(Collection&lt;? extends E&gt; items)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>同样的原理，在上面的代码可以改成这样：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">List&lt;String&gt; strs = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">strs.add(<span class="string">"0"</span>);</div><div class="line">objs.add(<span class="string">"1"</span>); </div><div class="line">List&lt;? extends Object&gt; objs = strs; <span class="comment">// OK</span></div></pre></td></tr></table></figure></p>
<h3 id="PECS"><a href="#PECS" class="headerlink" title="PECS"></a>PECS</h3><p><em>PECS stands for Producer-Extends,Consumer-Super</em>，具体的可以参考<a href="http://www.importnew.com/8966.html" target="_blank" rel="external">PECS</a>。</p>
<ul>
<li>通配符上界，只能从中读取元素，不能添加元素，称为生产者(Producers)，用<code>&lt;? extends T&gt;</code>表示。</li>
<li>通配符下界，只能添加元素，不能直接读取下界类型的元素，称为消费者(Consumers)，用<code>&lt;? super T&gt;</code>表示。</li>
</ul>
<h4 id="通配符上界"><a href="#通配符上界" class="headerlink" title="通配符上界"></a>通配符上界</h4><p><code>&lt;? extends T&gt;</code>(<code>T</code>表示通配符的上界)，表示可以接收<code>T</code>以及<code>T</code>的子类参数，也就是说可以安全的读取到<code>T</code>的实例，事实上所有的集合元素都是<code>T</code>的子类的实例，但不能向其添加元素，因为没法确定添加的实例类型跟定义的类型是否匹配，举个栗子：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">List&lt;String&gt; strs = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">strs.add(<span class="string">"0"</span>);</div><div class="line">strs.add(<span class="string">"1"</span>);</div><div class="line">List&lt;? extends Object&gt; objs = strs;</div><div class="line"><span class="comment">// 上面说过这样是可以</span></div><div class="line">objs.get(<span class="number">0</span>); <span class="comment">// 可以获取</span></div></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 但是再添加一个int类型的话</span></div><div class="line">objs.add(<span class="number">1</span>); <span class="comment">// 报错</span></div></pre></td></tr></table></figure>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-2fbaa3c0ba7c9be5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="objs.add(1)"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 再添加一个String类型</span></div><div class="line">objs.add(<span class="string">"1"</span>); <span class="comment">// 同样会报错</span></div></pre></td></tr></table></figure>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-80d92186bcfa4974.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="objs.add(&quot;1&quot;)"></p>
<p>上面的例子说明了<code>objs</code>可以读取值，但是再往<code>objs</code>里面添加值的时候，就会出错，没法确定添加的实例类型跟定义的类型是否匹配。</p>
<blockquote>
<p>这种<code>wildcard</code>是通过继承一个范围类(extends-bound)，也就是通配符上界(upper bound)来实现类型协变。</p>
</blockquote>
<h4 id="通配符下界"><a href="#通配符下界" class="headerlink" title="通配符下界"></a>通配符下界</h4><p>那么有通配符上界<code>&lt;? extends T&gt;</code>，自然就会有下界，<code>&lt;? super T&gt;</code>，其中<code>T</code>就表示通配符的下界。<br>举个栗子：<code>Collection&lt;? super String&gt;</code>是<code>Collection&lt;String&gt;</code>的父类型，所以可以直接<code>add</code>和<code>set</code>，但是<code>get</code>的时候获取到的类型是Object而不是String类型。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">List&lt;String&gt; strs = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">strs.add(<span class="string">"0"</span>);</div><div class="line">strs.add(<span class="string">"1"</span>);</div><div class="line">List&lt;? <span class="keyword">super</span> String&gt; objs = strs;</div><div class="line">objs.add(<span class="string">"1"</span>);</div><div class="line">objs.set(<span class="number">0</span>, <span class="string">"2"</span>);</div><div class="line">Object s = objs.get(<span class="number">0</span>);</div></pre></td></tr></table></figure></p>
<p>在Kotlin中，并没有上面的机制，而是通过<code>Declaration-site variance</code>和<code>Type projections</code>来执行的。</p>
<h2 id="声明位置变异-Declaration-site-variance"><a href="#声明位置变异-Declaration-site-variance" class="headerlink" title="声明位置变异(Declaration-site variance)"></a>声明位置变异(Declaration-site variance)</h2><p>声明位置变异：通过将参数<code>T</code>注解成只能作为返回值，不能作为传入参数；使用<code>out</code>关键字标识。<br>首先我们来看一下，在Java中，<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Source</span>&lt;<span class="title">T</span>&gt; </span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">nextT</span><span class="params">()</span></span>;</div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">demo</span><span class="params">(Source&lt;String&gt; strs)</span></span>&#123;</div><div class="line">    Source&lt;Object&gt; objs = strs; <span class="comment">// 在Java中是不允许的</span></div><div class="line">    <span class="comment">// 正确方式为</span></div><div class="line">    <span class="comment">// Source&lt;? extends Object&gt; objs = strs;</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在Kotlin中，使用声明位置变异来解决这种问题：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Source</span>&lt;<span class="type">out T</span>&gt; </span>&#123;</div><div class="line">    <span class="comment">// 使用out的话，T只能作为返回值</span></div><div class="line">    <span class="keyword">abstract</span> <span class="function"><span class="keyword">fun</span> <span class="title">nextT</span><span class="params">()</span></span>: T</div><div class="line">    <span class="comment">// 不能作为传入参数，下面会报错</span></div><div class="line">    <span class="comment">// abstract fun add(value: T)</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">demo</span><span class="params">(strs: <span class="type">Source</span>&lt;<span class="type">String</span>&gt;)</span></span> &#123;</div><div class="line">    <span class="keyword">val</span> objects: Source&lt;Any&gt; = strs</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>有<code>out</code>就有<code>in</code>，<code>in</code>与<code>out</code>互补，它使类型参数逆变<code>contravariant</code>，只能作为传入参数，不能作为返回值：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Source</span>&lt;<span class="type">in T</span>&gt; </span>&#123;</div><div class="line">    <span class="comment">// 使用in的话，只能作为传入参数，不能作为返回值</span></div><div class="line">    <span class="comment">// abstract fun nextT(): T</span></div><div class="line">    <span class="keyword">abstract</span> <span class="function"><span class="keyword">fun</span> <span class="title">add</span><span class="params">(value: <span class="type">T</span>)</span></span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">demo</span><span class="params">(strs: <span class="type">Source</span>&lt;<span class="type">Number</span>&gt;)</span></span> &#123;</div><div class="line">    <span class="keyword">val</span> objects: Source&lt;<span class="built_in">Double</span>&gt; = strs <span class="comment">// Double是Number的子类型</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>总结一下，当一个泛型类<code>C</code>，包含<code>out</code>关键字的时候，等同于Java的<code>extends</code>，将类<code>C</code>称为<code>T</code>的协变类，<code>T</code>只能作为该类中函数的返回类型，不能作为参数传递进来，也可以称类<code>C</code>为<code>T</code>的生产者(Producer)。</p>
<p>同理，当包含<code>in</code>关键字的时候，等同于Java的<code>super</code>，将类<code>C</code>称为<code>T</code>的逆变类，<code>T</code>只能作为该类中函数的参数传递进来，不能作为返回类型，也可以称类<code>C</code>为T的消费者(Consumer)。</p>
<p>可以将上面两段话总结成：</p>
<blockquote>
<p><strong>Consumer in, Producer out!</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function">fun <span class="title">copy</span><span class="params">(from: Array&lt;out String&gt;, to: Array&lt;in String&gt;)</span> </span>&#123;</div><div class="line">    <span class="keyword">assert</span>(from.size == to.size)</div><div class="line">    <span class="keyword">for</span> (i in from.indices)</div><div class="line">         to[i] = from[i]</div><div class="line">&#125;</div><div class="line"><span class="comment">// 等同于</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">copy</span><span class="params">(List&lt;? extends String&gt; from, List&lt;? <span class="keyword">super</span> String&gt; to)</span> </span>&#123; ... &#125;</div></pre></td></tr></table></figure>
<h3 id="Star-projections"><a href="#Star-projections" class="headerlink" title="Star-projections"></a>Star-projections</h3><p>在Kotlin中，定义一个该泛型类型的推测<code>projection</code>类型，使泛型类型的每一个具体实例应该是推测<code>projection</code>类型的子类型，称之为Star-projections，语法为：</p>
<ul>
<li>对于<code>Foo&lt;out T&gt;</code>：<code>T</code>是一个协变类型参数，可以知道<code>Foo&lt;*&gt;</code>是与之相等的，当<code>T</code>不可知时，可以安全的读取到<code>T</code>，可以通过<code>Foo&lt;*&gt;</code>得到<code>T</code>。</li>
<li>对于<code>Foo&lt;In T&gt;</code>：<code>T</code>是一个逆变类型参数，可以知道<code>Foo&lt;*&gt;</code>等同于<code>Foo&lt;in Nothing&gt;</code>，当<code>T</code>不可知时，不能在<code>Foo&lt;*&gt;</code>里面添加元素。</li>
<li>对于<code>Foo&lt;T&gt;</code>：<code>T</code>是一个不变类型参数，当从中读取数据时<code>Foo&lt;*&gt;</code>同等于<code>Foo&lt;out T&gt;</code>；当向其添加数据时，<code>Foo&lt;*&gt;</code>等同于<code>Foo&lt;in Nothing&gt;</code>。</li>
</ul>
<p>举个栗子，一个泛型定义<code>interface Function&lt;in T, out U&gt;</code>：</p>
<ol>
<li><code>Function&lt;*, String&gt;</code>等同于什么？<br>等同于<code>Function&lt;in Nothing, String&gt;</code></li>
<li><code>Function&lt;Int, *&gt;</code>等同于什么？<br>等同于<code>Function&lt;Int, out Any?&gt;</code></li>
<li><code>Function&lt;*, *&gt;</code>等同于什么？<br>等同于<code>Function&lt;in Nothing, out Any?&gt;</code></li>
</ol>
<h2 id="泛型函数-Generic-functions"><a href="#泛型函数-Generic-functions" class="headerlink" title="泛型函数(Generic functions)"></a>泛型函数(Generic functions)</h2><p>Kotlin同样支持泛型函数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T&gt;</span> <span class="title">singletonList</span><span class="params">(item: <span class="type">T</span>)</span></span>: List&lt;T&gt; &#123;</div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T&gt;</span> T.<span class="title">basicToString</span><span class="params">()</span></span> : String &#123;  <span class="comment">// extension function</span></div><div class="line">    <span class="comment">// ...</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>使用的时候，在函数名称后面指定具体的类型参数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">val</span> l = singletonList&lt;<span class="built_in">Int</span>&gt;(<span class="number">1</span>)</div></pre></td></tr></table></figure></p>
<h2 id="泛型约束-Generic-constraints"><a href="#泛型约束-Generic-constraints" class="headerlink" title="泛型约束(Generic constraints)"></a>泛型约束(Generic constraints)</h2><h3 id="Upper-bounds"><a href="#Upper-bounds" class="headerlink" title="Upper bounds"></a>Upper bounds</h3><p>Kotlin的泛型约束和类的继承一样，使用<code>:</code>代替<code>extends</code>对泛型的的类型上界进行约束：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">SwipeRefreshableView</span>&lt;<span class="type">T : View</span>&gt;</span>&#123;&#125;</div></pre></td></tr></table></figure></p>
<p>同时Kotlin支持多个类型的上界约束，使用<code>where</code>关键字：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">SwipeRefreshableView</span>&lt;<span class="type">T</span>&gt;</span></div><div class="line">    where T : View,</div><div class="line">          T : Refreshable &#123;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Jowan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://www.jowanxu.top/2017/05/31/Kotlin学习_泛型/" title="Kotlin学习_泛型（Generics）">http://www.jowanxu.top/2017/05/31/Kotlin学习_泛型/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kotlin/" rel="tag"><i class="fa fa-tag"></i> Kotlin</a>
          
            <a href="/tags/Generics/" rel="tag"><i class="fa fa-tag"></i> Generics</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/05/30/Kotlin学习_可见性修饰符和数据类/" rel="next" title="Kotlin学习_可见性修饰符和数据类">
                <i class="fa fa-chevron-left"></i> Kotlin学习_可见性修饰符和数据类
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/06/09/Kotlin实战_实现RecyclerView多种Item布局/" rel="prev" title="Kotlin实战_实现RecyclerView多种Item布局">
                Kotlin实战_实现RecyclerView多种Item布局 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjA1My84NjE3"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Jowan" />
          <p class="site-author-name" itemprop="name">Jowan</p>
           
              <p class="site-description motion-element" itemprop="description">叫我旺仔<br/>Android Developer</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">27</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://plus.google.com/u/0/111824269044709365866" target="_blank" title="Google">
                  
                    
                      Google
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/wangzailfm" target="_blank" title="GitHub">
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/809077554" target="_blank" title="微博">
                  
                    
                      微博
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="673173629@qq.com" target="_blank" title="E-Mail">
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/u011976726" target="_blank" title="CSDN">
                  
                    
                      CSDN
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/u/5509a21c1623" target="_blank" title="简书">
                  
                    
                      简书
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-block">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wanandroid.com/" title="WanAndroid" target="_blank">WanAndroid</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#泛型"><span class="nav-number">1.</span> <span class="nav-text">泛型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#变异-Variance"><span class="nav-number">2.</span> <span class="nav-text">变异(Variance)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#PECS"><span class="nav-number">2.1.</span> <span class="nav-text">PECS</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#通配符上界"><span class="nav-number">2.1.1.</span> <span class="nav-text">通配符上界</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通配符下界"><span class="nav-number">2.1.2.</span> <span class="nav-text">通配符下界</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#声明位置变异-Declaration-site-variance"><span class="nav-number">3.</span> <span class="nav-text">声明位置变异(Declaration-site variance)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Star-projections"><span class="nav-number">3.1.</span> <span class="nav-text">Star-projections</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#泛型函数-Generic-functions"><span class="nav-number">4.</span> <span class="nav-text">泛型函数(Generic functions)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#泛型约束-Generic-constraints"><span class="nav-number">5.</span> <span class="nav-text">泛型约束(Generic constraints)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Upper-bounds"><span class="nav-number">5.1.</span> <span class="nav-text">Upper bounds</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jowan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
